﻿using DoNetDrive.AspWebSocke;
using DoNetDrive.Core.Packet;
using DotNetty.Buffers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Face8280WebSocketServer.Command
{
    internal class JsonPacket : INPacket
    {
        public static Encoding JsonEncoding = Encoding.UTF8;

        private string JsonString;

        private byte[] BinaryData;

        private int BinaryDataLength;
        public PacketType PacketType { get; private set; }
        public JsonPacket(string jString, byte[] binaryData = null, int binaryDataLength = 0)
        {
            JsonString = jString;
            BinaryData = binaryData;
            BinaryDataLength = binaryDataLength;
            if (BinaryDataLength == 0 && BinaryData != null)
                BinaryDataLength = BinaryData.Length;
        }
        public string GetJson()
        {
            return JsonString;
        }
        public byte[] GetBinaryData()
        {
            return BinaryData;
        }
        public void SetJson(string value)
        {
            JsonString = value;
        }
        public void SetData(byte[] data, int len)
        {
            BinaryData = data;
            BinaryDataLength = len;
        }

        public void Dispose()
        {
        }

        public IByteBuffer GetPacketData(IByteBufferAllocator Allocator)
        {
            var sJson = GetJson();
            var iCount = JsonEncoding.GetByteCount(sJson);
            var bufLen = iCount + 4;
            if (BinaryData != null)
            {
                bufLen += BinaryDataLength;
            }
            var buf = Allocator.Buffer(bufLen);
            buf.WriteInt(iCount);
            buf.WriteBytes(JsonEncoding.GetBytes(sJson));
            if (BinaryData != null)
                buf.WriteBytes(BinaryData, 0, BinaryDataLength);
            return buf;
        }

        public IByteBuffer GetTextPacketData()
        {
            var sJson = GetJson();
            var buf = WebSocketUnpooled.WrappedTextBuffer(sJson, JsonEncoding);
            return buf;
        }

        public IByteBuffer GetBinaryPacketData()
        {
            if (BinaryData == null) return null;
            var buf = WebSocketUnpooled.WrappedBinaryBuffer(BinaryData);
            return buf;

        }

        public void ReleaseDataBuf()
        {

        }
    }
    public enum PacketType
    {
        Text,
        Binary,
    }
}
